/* 
* Copyright (C) 2011-2018 ShenZhen iBOXSaaS Information Technology Co.,Ltd. 
* 
* All right reserved. 
* 
* This software is the confidential and proprietary 
* information of iBOXSaaS Company of China. 
* ("Confidential Information"). You shall not disclose 
* such Confidential Information and shall use it only 
* in accordance with the terms of the contract agreement 
* you entered into with iBOXSaaS inc. 
* 
*/

package com.iboxpay.open.gateway.basedata;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties.ZuulRoute;
import org.springframework.stereotype.Component;

import com.iboxpay.open.common.db.dao.ResUrlRecordDao;
import com.iboxpay.open.common.db.entity.AuthTokenScope;
import com.iboxpay.open.common.db.entity.ResUrlRecord;
import com.iboxpay.open.gateway.vo.ResScopeVo;

/**
 * 
 * BaseData.java
 * @author xuxiao
 * @date 2018/06/15
 */
@Component
public class BaseData {
	
	@Autowired
	private ResUrlRecordDao resUrlRecordDao;
	
	
	public Map<String, ZuulRoute> zuulRouteMap = new LinkedHashMap<>();
	
	public Map<String, ResScopeVo> resTokenCheckMap = new HashMap<>();
	
	@PostConstruct
	public void init() {
		loadResRecord();
	}
	
	/**
	 * 加载资源记录
	 */
	private void loadResRecord() {
		Map<String, ZuulRoute> routeTmp = new LinkedHashMap<>();
		Map<String, ResScopeVo> scopeTmp = new HashMap<>();
		List<ResUrlRecord> resUrlRecordList = resUrlRecordDao.selectAllAboutScope();
		for(ResUrlRecord entry : resUrlRecordList) {
			ZuulRoute route = new ZuulRoute();
			route.setId(entry.getResCode());
			route.setPath(entry.getPath());
			route.setRetryable(entry.getRetryable());
			route.setServiceId(entry.getServiceId());
			route.setStripPrefix(entry.getStripPrefix());
			route.setUrl(entry.getUrl());
			routeTmp.put(entry.getPath(), route);
			
			Set<String> scopeCodeSet = new HashSet<>();
			for(AuthTokenScope tmp : entry.getAuthTokenScopes()) {
				scopeCodeSet.add(tmp.getScopeCode());
			}
			
			ResScopeVo resScope = new ResScopeVo();
			resScope.setPath(entry.getPath());
			resScope.setScopeCode(scopeCodeSet);
			resScope.setVerifyToken(entry.getTokenCheck());
			scopeTmp.put(entry.getPath(), resScope);
		}
		
		zuulRouteMap.putAll(routeTmp);
		resTokenCheckMap.putAll(scopeTmp);
	}
	
}
